<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <title>JQ实现弹幕效果</title>
    <style type="text/css">
        * {
            padding: 0;
            margin: 0;
        }

        #box {
            height: 650px;
            width: 1000px;
            margin: 0 auto;
            border: 1px solid #000000;
            position: relative;
        }

        #main {
            width: 100%;
            height: 550px;
            position: relative;
            overflow: hidden;
        }

        p {
            position: absolute;
            left: 1000px;
            width: 200px;
            top: 0;
        }

        #bottom {
            width: 100%;
            height: 80px;
            background: #ABCDEF;
            text-align: center;
            padding-top: 15px;
            position: absolute;
            left: 0;
            bottom: 0;
        }

        #txt {
            width: 300px;
            height: 50px;
        }

        #btn {
            width: 100px;
            height: 50px;
        }
    </style>
</head>

<body>
    <div id="box">
        <div id="main">

        </div>
        <div id="bottom">
            <input type="text" id="txt" placeholder="请输入内容" />
            <input type="button" id="btn" value="发射" />
        </div>
    </div>
    <script src="jquery-1.11.3.js"></script>
    <script type="text/javascript">
        $(function () {
            var pageH = parseInt($("#main").height()-$("p").height());
            var colorArr = ["#cfaf12", "#12af01", "#981234", "#adefsa", "#db6be4", "#f5264c", "#d34a74"];

            var msgArr = new Array();
            function sendMsg() {
                msgArr = new Array();
                msgArr.push($("<p>" + $("#txt").val() + "</p>"));
                $("#txt").val("");  // 获取输入内容
                $("#main").append(msgArr);  //先将弹幕加入Array,再一次性呈现出来,减少dom循环
                $.each(msgArr, function (i) {
                    var $this = msgArr[i];
                    var _top = parseInt(pageH * (Math.random()));
                    var num = parseInt(colorArr.length * (Math.random()));
                    $this.css({ "top": _top, "color": colorArr[num], "font-size": "20px" });
                    $this.animate({ "left": "-200px" }, 10000);
                    $this.stop().animate({ "left": "-300px" }, 10000, "linear", function () {
                        $(this).remove();
                    });
                });
                msgArr = new Array();
            }
            $("#btn").bind("click", sendMsg);
            document.onkeydown = function (e) {
                if (e.keyCode == 13)
                    sendMsg();
            };
        })
    </script>
</body>

</html>